// dw-role
import Vue from 'vue'
import DwAuthorized from './authorized'

function changeHasRole(el, binding) {
  if (!roleCheck(binding.value)) {
    el.parentNode.removeChild(el)
  }

  function roleCheck(value) {
    const authority = DwAuthorized.getAuthority()
    for (let i = 0; i < authority.length; i++) {
      if (value === authority[i]) {
        return true
      }
    }
    return false
  }
}

Vue.directive('hasDwRole', {
  inserted: function (el, binding) {
    changeHasRole(el, binding)
  }
})

// "2018-05-19T08:04:52.000+0000"这种格式的时间转化为正常格式
export function DateFormat(date) {
  if(date == '' || date == null || date == undefined)
    return ''

  var d = new Date(date);

  var year = d.getFullYear();       //年
  var month = d.getMonth() + 1;     //月
  var day = d.getDate();            //日

  var clock = year + "-";

  if (month < 10)
    clock += "0";

  clock += month + "-";

  if (day < 10)
    clock += "0";

  clock += day

  return (clock);
}
//存在问题时间相差八个小时
export function exactDateFormat(date) {
  if(date == '' || date == null || date == undefined)
    return ''

  var d = new Date(date);

  var year = d.getFullYear();       //年
  var month = d.getMonth() + 1;     //月
  var day = d.getDate();            //日
  var hour = d.getHours();
  var minute = d.getMinutes();
  var second = d.getSeconds();

  var clock = year + "-";

  if (month < 10)
    clock += "0";

  clock += month + "-";

  if (day < 10)
    clock += "0";

  clock += day

  clock += " ";

  if (hour < 10)
    clock += "0";

  clock += hour + ":";

  if (minute < 10)
    clock += "0";

  clock += minute + ":";

  if (second < 10)
    clock += "0";

  clock += second

  return (clock);
}


/**
 * 排序比较
 * @param {string} propertyName 排序的属性
 * @param {string} sort ascending(升序)/descending(降序)
 * @return {function}
 */
export function compare(propertyName, sort) {
  return function (obj1, obj2) {
    var value1 = obj1[propertyName]
    var value2 = obj2[propertyName]
    if (typeof value1 === 'string' && typeof value2 === 'string') {
      const res = value1.localeCompare(value2, 'zh')
      return sort === 'ascending' ? res : -res
    } else {
      if (value1 <= value2) {
        return sort === 'ascending' ? -1 : 1
      } else if (value1 > value2) {
        return sort === 'ascending' ? 1 : -1
      }
    }
  }
}
